package com.gator.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;


public class PABLO_KafkaConsumer3 extends Thread{

    KafkaConsumer<Integer,String> consumer;
    String topic;

    public PABLO_KafkaConsumer3(String topic) {
        Properties properties=new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092,localhost:9093,localhost:9094");
        properties.put(ConsumerConfig.CLIENT_ID_CONFIG,"pablo-consumer");
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"pablo_group_1");
        properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG,"30000");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
        consumer=new KafkaConsumer<Integer, String>(properties);
        this.topic = topic;
    }


    @Override
    public void run() {
        consumer.subscribe(Collections.singleton(this.topic));

        while (true) {
            //这里可设置一个Boolean/interrupt，用于打断，避免空轮询
            //Duration.ofSeconds(1)设置1S拉取一次
            ConsumerRecords<Integer, String> consumerRecords = consumer.poll(Duration.ofSeconds(1));
            consumerRecords.forEach(record -> {
                System.out.println(record);
            });

        }
    }

    public static void main(String[] args) {
        new PABLO_KafkaConsumer3("test_partitions").start();
    }
}
